package com.zxjbyte.yiyi.framework.common.core.pdf.event;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.zxjbyte.yiyi.framework.common.core.pdf.PdfHelper;

/**
 * 单行文本水印，默认顺时针旋转45度
 * @Author zhangxingjia
 * @Date 2023/3/24 13:47
 * @Version: 1.0
 */
public class SingleTextWatermark extends PdfPageEventHelper {

    // 水印文本内容
    private final String text;
    // 水印字体大小 默认: 80
    private final float size;

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        try {
            BaseFont baseFont = PdfHelper.getChineseBaseFont();
            Font font = new Font(baseFont, size, Font.NORMAL, BaseColor.LIGHT_GRAY);
            // 获取PdfContentByte对象，向当前页面添加元素
            PdfContentByte canvas = writer.getDirectContent();
            // 设置水印透明度
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.2f);
            canvas.setGState(gs);
            // 获取页面大小
            Rectangle pageRect = document.getPageSize();
            // 水印坐标居中计算 基于文档宽和高
            float x = (pageRect.getWidth()) / 2;
            float y = (pageRect.getHeight()) / 2;
            // 创建一个Phrase对象，用于存储水印文本
            Phrase phrase = new Phrase(text, font);
            // 添加水印 旋转角度45度
            ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase, x, y, 45);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public SingleTextWatermark(String text) {
        this(text, 80);
    }

    public SingleTextWatermark(String text, float size) {
        this.text = text;
        this.size = size;
    }
}
